package com.bgs.controller;


import com.alibaba.fastjson.JSONObject;
import com.bgs.client.OrderDetailClient;
import com.alibaba.fastjson.JSON;
import com.bgs.common.R;
import com.bgs.pojo.Circle;
import com.bgs.pojo.FocusOn;
import com.bgs.pojo.Store;
import com.bgs.pojo.vo.*;
import com.bgs.service.CircleImgService;
import com.bgs.service.CircleService;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.*;

/**
 * <p>
 * 圈子 前端控制器
 * </p>
 *
 * @author Asia
 * @since 2021-09-14
 */
@RestController
@RequestMapping("/bgs/circle")
public class CircleController {
    @Autowired
    private CircleService circleService;
    @Autowired
    private OrderDetailClient orderDetailClient;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 后台圈子审核查看
     * @param beforeUserName
     * @param orderDetailId
     * @return
     */
    @GetMapping("/TowGettableDataQuan")
    public R TowGettableDataQuan(String beforeUserName,Integer orderDetailId){
        List<Circle> list = circleService.TowGettableDataQuan(beforeUserName,orderDetailId);
        return R.ok().data("list",list);
    }

    @GetMapping("/TowGetData")
    public R TowGetData(Integer beforeUserId){
        //店铺
        List<FocusOnTow> list = circleService.TowGetData(beforeUserId);
        list.stream().forEach(x->{
            //店铺发布的圈子
            List<CircleTow> circleTows = circleService.TowGetCircle(x.getStoreId());
            circleTows.stream().forEach(y->{
                List<OrderDetail> orderDetailTows = orderDetailClient.TowgetOrderDetail(y.getOrderDetailId());
                y.setOrderDetails(orderDetailTows);
            });
            x.setCircleTows(circleTows);
        });
        return R.ok().data("list",list);
    }

    /**
     * 发布圈子
     * @return
     */
    @PostMapping("/TowAddCircle")
    public R TowAddCircle(@RequestBody Map map){
        String content = map.get("content").toString();
        String beforeUserId = map.get("beforeUserId").toString();
        int i1 = Integer.parseInt(beforeUserId);
        Integer orderDetailId =Integer.parseInt(map.get("orderDetailId").toString());
        Integer storeId =Integer.parseInt( map.get("storeId").toString());
        Circle circle = new Circle();
        circle.setCircleText(content);
        circle.setBeforeUserId(i1);
        circle.setOrderDetailId(orderDetailId);
        circle.setCircleCreateTime(new Date());
        circle.setStoreId(storeId);
        int i = circleService.TowAddCircle(circle);
        return R.ok().data("i",i);
    }

    @PostMapping("/TowAddShop")
    public R TowAddShop(@RequestBody Map map){
        Boolean flag = true;
        String shopList = JSONObject.toJSONString(map.get("shopList"));
        ShopAdd shopAdd1 = JSONObject.parseObject(shopList, ShopAdd.class);
        Integer beforeUserId = shopAdd1.getBeforeUserId();
        shopAdd1.setFlag(flag);
        if(redisTemplate.hasKey(beforeUserId+"gouWu")){
            List range = redisTemplate.opsForList().range(beforeUserId + "gouWu", 0, -1);
            range.stream().forEach(x->{
                //如果有这个商品
                ShopAdd shopAdd = JSON.parseObject(x.toString(), ShopAdd.class);
                if(shopAdd1.getShangpinid().equals(shopAdd.getShangpinid())){
                    String concat = shopAdd.getConcat();
                    shopAdd1.setConcat(shopAdd.getConcat()+concat);
                    redisTemplate.opsForList().remove(beforeUserId+"gouWu",0,shopAdd);
                }
            });
        }
        redisTemplate.opsForList().leftPush(beforeUserId+"gouWu",shopAdd1);
        return R.ok().message("添加购物车成功");
    }
    @GetMapping("/TowListShop")
    public R TowListShop(Integer beforeUserId){
        if(redisTemplate.hasKey(beforeUserId+"gouWu")){
            List range = redisTemplate.opsForList().range(beforeUserId + "gouWu", 0, -1);
            return R.ok().data("list",range);
        }
        return R.ok().message("去加购商品");
    }

    /**
     * 圈子点赞
     * 评论点赞
     * comments_id评论
     * circle_id圈子
     * before_user_id用户
     * [
     * {
     * "circleId":1,
     * "commentsId":3,
     * "beforeUserId":1,
     * "likeId":1
     * }
     * ]
     */
    @PostMapping("ZeroAllCircleAndComments")
    //全查出评论list，取出里面的东西封装到集合里，传给该方法
    public void ZeroAllCircleAndComments(@RequestBody List<ZeroLike> zeroLike) {
//key为list类型(圈子id，评论id)或者、int数组，
// value为用户id累加，通过长度获取点赞数
//        //list长度
//        redisTemplate.opsForList().size("list4");
//        //有则添加，无则创建加添加
//        redisTemplate.opsForList().rightPush("list4", "one");
//        //删除
//        redisTemplate.opsForList().remove("list4", 1, "two");
//        //遍历redis
//        for (int i = 0; i < redisTemplate.opsForList().size("list4"); i++) {
//            System.out.println(redisTemplate.opsForList().index("list4", i));
//        }
        System.out.println(zeroLike);
        List arrayList = new ArrayList<ZeroLike>();
        for (int i = 0; i < zeroLike.size(); i++) {
            /**圈子点赞
             * 1.如果redis有该圈子id、用户id（该字段非表内id，为登录用户id），则点赞为高光
             * 2.高光状态，点赞后，将redis内圈子id与用户id删除
             * 3.灰色状态，点赞后，redis存入圈子id与用户id
             */
            if (zeroLike.get(i).getCircleId() != null && zeroLike.get(i).getBeforeUserId() != null) {
                /**redis
                 * 先判断是否触发点赞
                 * key不能重复{1.指定分库储存，2.将评论id设很大，保证id不会重复}
                 * 1.查询是否有该key，有则返回true，无则false
                 * 2.点击后，判断是否有key，有则删除，无则创建
                 */
//                if (zeroLike.get(i).getLikeId() == 0) {
//                    //圈子
//                    redisTemplate.opsForList().remove(
//                            zeroLike.get(0).getCircleId(),
//                            1,
//                            zeroLike.get(0).getBeforeUserId()
//                    );
                    //这是评论
//                     for (int q = 0; q < redisTemplate.opsForList().size(zeroLike.get(i).getCircleId()); q++) {
//                        System.out.println(redisTemplate.opsForList().index(zeroLike.get(i).getCircleId(), q));
//                        if(zeroLike.get(i).getLikeId() == redisTemplate.opsForList().index(zeroLike.get(i).getCircleId(), q)){
//                            redisTemplate.opsForList().remove(zeroLike.get(i).getCircleId(), 1, redisTemplate.opsForList().index(zeroLike.get(i).getCircleId(),q));
//                        }
//                     }
                }
//                if (zeroLike.get(i).getLikeId() == 1) {
//                    redisTemplate.opsForList().rightPush(
//                            zeroLike.get(0).getCircleId(),
//                            zeroLike.get(0).getBeforeUserId()
//                    );
//                }
                if (zeroLike.get(i).getLikeId() == null) {
//                    for (int q = 0; q < redisTemplate.opsForList().size(zeroLike.get(i).getCircleId()); q++) {
//                    }
                    //扔一个圈子id和用户id看是否有值，
                    //有则存入
//                    zeroLike.get(i).getCircleId(),
//                            zeroLike.get(i).getBeforeUserId()
                }

                Boolean key2 = redisTemplate.opsForList().getOperations().hasKey(zeroLike.get(i).getCircleId());
                System.out.println(key2);
            }
            /**评论点赞
             * 没有回复目标id，则为父评论
             * 1.如果redis有该评论id、用户id（该字段非表内id，为登录用户id），则点赞为高光
             * 2.高光状态，点赞后，将redis内评论id与用户id删除
             * 3.灰色状态，点赞后，redis存入评论id与用户id
             */
//            if(zeroLike.get(i).getCommentsId() != null && zeroLike.get(i).getBeforeUserId() != null){
//                System.out.println(zeroLike.get(i).getCommentsId());
//                System.out.println(zeroLike.get(i).getBeforeUserId());
//                /**redis
//                 * 1.查询是否有该key，有则返回true，无则false
//                 * 2.点击后，判断是否有key，有则删除，无则创建
//                 */
//            }
        }
        //评论点赞
//        System.out.println(redisTemplate);
//        Boolean key2 = redisTemplate.opsForList().getOperations().hasKey("key2");
//        System.out.println(key2);
//        return R.ok().data("");



    @PostMapping("ZeroAllCircle")
    public R ZeroAllCircle(@RequestBody ZeroLike zeroLike) {
        //如果圈子id不存在
        if (!redisTemplate.hasKey("CircleId" + zeroLike.getCircleId())) {
            redisTemplate.opsForZSet().add("CircleId" + zeroLike.getCircleId(), zeroLike.getBeforeUserId(), 1);
        } else {
            //圈子存在
            Double score = redisTemplate.opsForZSet().score("CircleId" + zeroLike.getCircleId(), zeroLike.getBeforeUserId());
            if (zeroLike.getBeforeUserId() != null) {
                if (score != null) {
                    redisTemplate.opsForZSet().remove("CircleId" + zeroLike.getCircleId(), zeroLike.getBeforeUserId());
                } else {
                    redisTemplate.opsForZSet().add("CircleId" + zeroLike.getCircleId(), zeroLike.getBeforeUserId(), 1);
                }
            }
        }
        Set set1 = redisTemplate.opsForZSet().rangeWithScores("CircleId" + zeroLike.getCircleId(), 0, -1);
        return R.ok().data("set1", set1);
    }

    @PostMapping("ZeroAllComments")
    public R ZeroAllComments(@RequestBody ZeroLike zeroLike) {
        //如果评论id不存在
        if (!redisTemplate.hasKey("CommentsId" + zeroLike.getCommentsId())) {
            redisTemplate.opsForZSet().add("CommentsId" + zeroLike.getCommentsId(), zeroLike.getBeforeUserId(), 1);
        } else {
            //评论存在
            Double score = redisTemplate.opsForZSet().score("CommentsId" + zeroLike.getCommentsId(), zeroLike.getBeforeUserId());
            if (zeroLike.getBeforeUserId() != null) {
                if (score != null) {
                    redisTemplate.opsForZSet().remove("CommentsId" + zeroLike.getCommentsId(), zeroLike.getBeforeUserId());
                } else {
                    redisTemplate.opsForZSet().add("CommentsId" + zeroLike.getCommentsId(), zeroLike.getBeforeUserId(), 1);
                }
            }
        }
        Set set2 = redisTemplate.opsForZSet().rangeWithScores("CommentsId" + zeroLike.getCommentsId(), 0, -1);
        return R.ok().data("set2", set2);
    }

    @PostMapping("ZeroAllOrderDetail")
    public R ZeroAllOrderDetail(@RequestBody ZeroLike zeroLike) {
        //如果评论id不存在
        if (!redisTemplate.hasKey("OrderDetailId" + zeroLike.getOrderDetailId())) {
            redisTemplate.opsForZSet().add("OrderDetailId" + zeroLike.getOrderDetailId(), zeroLike.getBeforeUserId(), 1);
        } else {
            //商品存在
            Double score = redisTemplate.opsForZSet().score("OrderDetailId" + zeroLike.getOrderDetailId(), zeroLike.getBeforeUserId());
            if (zeroLike.getBeforeUserId() != null) {
                if (score != null) {
                    redisTemplate.opsForZSet().remove("OrderDetailId" + zeroLike.getOrderDetailId(), zeroLike.getBeforeUserId());
                } else {
                    redisTemplate.opsForZSet().add("OrderDetailId" + zeroLike.getOrderDetailId(), zeroLike.getBeforeUserId(), 1);
                }
            }
        }
        Set set3 = redisTemplate.opsForZSet().rangeWithScores("OrderDetailId" + zeroLike.getOrderDetailId(), 0, -1);
        return R.ok().data("set3", set3);
    }
}